<?php

//add a custom rest api endpoint

add_action( 'rest_api_init', function () {

	register_rest_route('b2/v1','/insertProduct',array(
		'methods'=>'post',
		'callback'=> 'insert_product_hunt',
		'permission_callback' => is_user_logged_in()
	));

    register_rest_route('b2/v1','/get-all-products',array(
        'methods'=>'get',
        'callback'=> 'get_all_product_hunt_products',
        'permission_callback' => '__return_true'
    ));
});

function insert_product_hunt( $request ) {
	if(!b2_check_repo()) return new \WP_Error('user_error',__('操作频次过高','b2'),array('status'=>403));
	$res = insert_product($request->get_params());

	if(isset($res['error'])){
		return new \WP_Error('pay_error',$res['error'],array('status'=>403));
	}else{
		return new \WP_REST_Response($res,200);
	}
}

function insert_product($data){
	$user_id = b2_get_current_user_id();
    if(!$user_id) return array('error'=>__('请先登录','b2'));

    return array('error'=>__($data,'b2'));

    wp_set_current_user($user_id);

    if($data['type'] !== 'draft'){
        $data['type'] = 'pending';
    }else{
        $data['type'] = 'draft';
    }

    if($data['post_id']){
        $post_author = get_post_field( 'post_author', $data['post_id'] );
    }

    $arg = array(
        'ID'=> $data['post_id'] ? $data['post_id'] : null,
        'post_title' => $data['title'],
        'post_content' => wp_slash($data['content']),
        'post_status' => $data['type'],
        'post_author' => $post_author,
        'post_category' => $data['cats'],
        'post_excerpt'=>$data['excerpt'],
    );

    if($data['post_id']){
        $post_id = wp_update_post($arg);
    }else{
        $post_id = wp_insert_post( $arg );
    }

}

function get_all_product_hunt_products()
{
    return 'all products';
}
